package com.dao;

import com.domain.UserEntity;
import com.util.SimpleJdbcUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;


public class UserDaoImpl implements UserDao {

    Connection conn;
    Statement st;
    ResultSet rs;

    @Override
    public List getAll() {
        String sql = "select * from t_user";

        System.out.println(sql);
        List<UserEntity> lists = SimpleJdbcUtil.queryResult(sql, null, UserEntity.class);
        System.out.println(lists);

        return lists;
    }

    @Override
    public UserEntity getStudent(int sno, String pwd) {
        String password = SimpleJdbcUtil.getPassword();

        try {

            Class.forName("com.mysql.jdbc.Driver");

            this.conn = DriverManager.getConnection
                    ("jdbc:mysql://127.0.0.1:3306/javaweb", "root", "lik");


            st = this.conn.createStatement();
            String sqlStr = String.format("select * from t_user where id=%d and pwd='%s'", sno, pwd);

            System.out.println(sqlStr);

            rs = st.executeQuery(sqlStr);

            rs.next();

            UserEntity userEntity = new UserEntity();

            userEntity.setId(rs.getInt(1));
            userEntity.setUsername(rs.getString(2));
            userEntity.setPwd(rs.getString(3));
            userEntity.setSex(rs.getInt(4));
            userEntity.setAddress(rs.getString(5));
            userEntity.setHobby(rs.getString(6));
            userEntity.setSno(rs.getInt(7));


            return userEntity;

        } catch (Exception e) {
            System.out.println("mysql connect error");

            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
                this.conn.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return null;
    }

    @Override
    public int saveStudent(UserEntity userEntity) {
        String sql = String.format("INSERT INTO `t_user` (`username`,`pwd`,`sex`,`address`,`hobby`,`sno`)VALUES ('%s','%s','%s','%s','%s',%s);"
                , userEntity.getUsername(), userEntity.getPwd(), userEntity.getSex(), userEntity.getAddress(), userEntity.getHobby(), userEntity.getSno());

        System.out.println(sql);
        return SimpleJdbcUtil.execute(sql, null);
    }

    @Override
    public void updatePassword(int userId, String pwd) {
        String sql = String.format("UPDATE `t_user` SET pwd=%s WHERE id=%d",pwd,userId);

        System.out.println(sql);

        SimpleJdbcUtil.execute(sql, null);
    }

}
